package com.supergzt.utils;


import com.supergzt.constant.SecurityConstants;
import com.supergzt.constant.ValidateMessageConstants;
import com.supergzt.context.SecurityContextHolder;
import com.supergzt.entity.base.LoginUser;
import com.supergzt.enums.HttpEnum;
import com.supergzt.exception.NoLoginException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

import javax.servlet.http.HttpServletRequest;

/**
 * @author 张钧
 * @Description
 * @create 2022-09-24 16:25
 */
public class SecurityUtils {
	public static String getToken(HttpServletRequest request) {
		return request.getHeader(SecurityConstants.AUTHORIZATION);
	}

	public static String encryptPassword(String password) {
		BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
		return passwordEncoder.encode(password);
	}

	/**
	 * 判断密码是否相同
	 * @param rawPassword     真实密码
	 * @param encodedPassword 加密后字符
	 * @return 结果
	 */
	public static boolean matchesPassword(String rawPassword, String encodedPassword) {
		BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
		return passwordEncoder.matches(rawPassword, encodedPassword);
	}

	public static LoginUser getLoginUser() {
		LoginUser loginUser = SecurityContextHolder.getLoginUser();
		if(loginUser == null){
			throw new NoLoginException(HttpEnum.ILLEGAL_TOKEN, ValidateMessageConstants.WRONG_TOKEN);
		}
		return loginUser;
	}
}
